<?php

class App {

    protected $controller = DEFAULT_CONTROLLER;
    protected $action = DEFAULT_ACTION;
    protected $verb = 'GET';

    /**
     * Route the request. If the controller implements 
     * IExceptionHandler, activate exception handling.
     */
    public function __construct() {
        $url = $this->parseUrl();

        if (file_exists('app/controllers/' . $url[0] . '.php')) {
            $this->controller = $url[0];
            unset($url[0]);
        }

        require_once 'app/controllers/' . $this->controller . '.php';

        $this->controller = new $this->controller;

        if ($this->controller instanceof IExceptionHandler) {
            set_exception_handler([$this->controller, 'ExceptionHandler']);
        }

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $this->verb = 'POST';
        }

        if (isset($url[1])) {
            if (method_exists($this->controller, $this->applyPattern($url[1]))) {
                $this->action = $url[1];
                unset($url[1]);
            }
        }

        $this->controller->route([$this->controller, $this->applyPattern($this->action)]/* , $this->verb, $url */);
    }

    /**
     * Strip slash from the end,
     * sanitize as a url,
     * then split it on slashes
     * @return String
     */
    protected function parseUrl() {
        if (isset($_GET['url'])) {
            return $url = explode('/', filter_var(rtrim($_GET['url'], '/'), FILTER_SANITIZE_URL));
        }
    }

    /**
     * Action methods are named using pattern <HTTP verb>_<action name>
     * @param String $action
     * @return String
     */
    protected function applyPattern($action) {
        return $this->verb . '_' . $action;
    }

}
